package com.jhf.skypac_pda.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.jhf.skypac_pda.db.gen.DaoMaster;
import com.jhf.skypac_pda.db.gen.DaoSession;

public class DBManager {



    private static DBManager instance;
    private DaoMaster.DevOpenHelper openHelper;
    private Context context;
    private DaoSession daoSession;
    private DaoMaster daoMaster;
    /**
     * 数据库文件名称
     */
    private final static String DB_DATA = "db_data";

    private DBManager(Context context) {
        this.context = context;
        openHelper = new DaoMaster.DevOpenHelper(context, DB_DATA, null);
    }


    public synchronized static DBManager getInstance(Context context) {
        if (instance == null) {
            instance = new DBManager(context);
        }
        return instance;
    }

    /**
     * 获取可读数据库
     */
    public synchronized SQLiteDatabase getReadableDatabase() {
        if (openHelper == null) {
            openHelper = new DaoMaster.DevOpenHelper(context, DB_DATA, null);
        }
        SQLiteDatabase db = openHelper.getReadableDatabase();
        return db;
    }

    /**
     * 获取可写数据库
     */
    public synchronized SQLiteDatabase getWritableDatabase() {
        if (openHelper == null) {
            openHelper = new DaoMaster.DevOpenHelper(context, DB_DATA, null);
        }
        SQLiteDatabase db = openHelper.getWritableDatabase();
        return db;
    }

    /**
     * 获取session
     * @param context
     * @return
     */
    public synchronized DaoSession getDaoSession(
            Context context) {
        if (daoSession == null) {
            if (daoMaster == null) {
                daoMaster = getDaoMaster(context, DB_DATA,
                        daoMaster);
            }
           daoSession =daoMaster.newSession();
        }
        return daoSession;
    }

    /**
     * 获取master
     * @param context
     * @param dbName
     * @param daoMaster
     * @return
     */
    public static synchronized DaoMaster getDaoMaster(
            Context context, String dbName,
            DaoMaster daoMaster) {
        if (daoMaster == null) {
            DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(
                    context, dbName, null);
            daoMaster = new DaoMaster(
                    helper.getWritableDatabase());
        }
        return daoMaster;
    }
}
